package br.ufpi.hu.prescricao.managedbeans;

import java.lang.reflect.Method;
import java.util.Comparator;

import org.primefaces.model.SortOrder;

import br.ufpi.hu.prescricao.model.Laudo;

public class LazySorterLaudo implements Comparator<Laudo> {

    private String sortField;
    
    private SortOrder sortOrder;
    
    public LazySorterLaudo(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }
    
    private String methodName(String field) throws ClassNotFoundException {
    	
    	Class<?> c = Class.forName("br.ufpi.hu.prescricao.model.Laudo");
    	
    	for (Method method : c.getDeclaredMethods()) {
    		String methodName = method.getName().toLowerCase();
			if (methodName.contains(field.toLowerCase()) && methodName.contains("get")) {
				return method.getName();
			}
		}
    	
    	return "";
    }
    

    public int compare(Laudo car1, Laudo car2) {
        try {
        	
        	Class<?> c = Class.forName("br.ufpi.hu.prescricao.model.Laudo");
        	Method  method = c.getDeclaredMethod (methodName(sortField));
        	Object value1 = method.invoke (car1);
        	Object value2 = method.invoke (car2);
        	
            @SuppressWarnings({ "unchecked", "rawtypes" })
			int value = ((Comparable)value1).compareTo(value2);
            
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        }
        catch(Exception e) {
        	e.printStackTrace();
            throw new RuntimeException();
        }
    }

}